﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

namespace MetadataMigrator
{
    public partial class UpdateMMFields : Form
    {
        public SPSite current_site;
        public TaxonomySession session;

        public UpdateMMFields()
        {
            InitializeComponent();
        }

        private void UpdateMMFields_FormClosing(Object sender, FormClosingEventArgs e)
        {
            current_site.Dispose();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            current_site = new SPSite(txtSiteURL.Text);
            session = new TaxonomySession(current_site);
            foreach (SPWeb web in current_site.AllWebs)
            {
                lstWebs.Items.Add(web.Url);
                web.Dispose();
            }
            Cursor.Current = Cursors.Default;
        }

        private void lstWebs_SelectedIndexChanged(object sender, EventArgs e)
        {
            SPWeb selected_web = current_site.OpenWeb(lstWebs.SelectedItem.ToString());

            //Get disconnected fields
            foreach (SPList list in selected_web.Lists)
            {
                foreach (SPField field in list.Fields)
                {
                    if (field.TypeAsString == "TaxonomyFieldType")
                    {
                        TaxonomyField tfield = field as TaxonomyField;
                        TermStore termstore;
                        try
                        {
                            termstore = session.TermStores[tfield.SspId];
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            lstDisconnectedFields.Items.Add(tfield.Title + " in list " + list.Title);
                        }
                    }
                }
            }
            selected_web.Dispose();
        }
    }
}
